package main

import (
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"
	"os"
	"yunzhan/api-server/internal/config"
	"yunzhan/api-server/internal/handler"
	"yunzhan/api-server/internal/svc"
)

var configFile = flag.String("f", "etc/config.yaml", "the config file")

const banner = `
 _     _             ___               ______  _           _                     _____             
| |   | |           / __)             (____  \(_)         | |      _            / ___ \            
| |___| |   _ ____ | |__ ____ ____     ____)  )_  ____  _ | | ____| |_  ____   | |   | |____   ___ 
 \_____/ | | |  _ \|  __) _  |  _ \   |  __  (| |/ _  |/ || |/ _  |  _)/ _  |  | |   | |  _ \ /___)
   ___ | |_| | | | | | ( ( | | | | |  | |__)  ) ( ( | ( (_| ( ( | | |_( ( | |  | |___| | | | |___ |
  (___) \____|_| |_|_|  \_||_|_| |_|  |______/|_|\_|| |\____|\_||_|\___)_||_|   \_____/| ||_/(___/ 
                                                (_____|                                |_|                                                
`

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	logx.MustSetup(c.ServicesLogConfig["apiServer"].LogConf)
	if c.ServicesLogConfig["apiServer"].LogConf.Mode == "file" {
		logFilePath := fmt.Sprintf(`%s/api-server.log`, c.ServicesLogConfig["apiServer"].LogConf.Path)
		file, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			logx.Error(err)
			return
		}
		defer file.Close()
		writer := logx.NewWriter(file)
		logx.SetWriter(writer)
	}

	defer func() {
		err := logx.Close()
		if err != nil {
			panic(err)
		}
	}()

	fmt.Print(banner)
	serviceConfig, ok := c.RestServices["apiServer"]
	if !ok {
		logx.Errorf("Service %s not found in config file", "api-server")
	}

	server := rest.MustNewServer(serviceConfig.RestConf)

	//server := rest.MustNewServer(serviceConfig.RestConf, rest.WithCustomCors(nil, func(w http.ResponseWriter) {
	//	w.Header().Set("Access-Control-Allow-Origin", "*")
	//	w.Header().Set("Access-Control-Allow-Headers", "*")
	//	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
	//	w.Header().Set("Access-Control-Expose-Headers", "Content-Length, Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
	//	w.Header().Set("Access-Control-Allow-Credentials", "true")
	//}, "*"))
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	logx.Infof("Starting %s at http://%s:%d", serviceConfig.RestConf.Name, serviceConfig.RestConf.Host, serviceConfig.RestConf.Port)
	server.Start()
}
